package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.dto.UnLikesBehaviorDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApUnlikesBehavior;
import com.heima.behavior.mapper.ApUnlikesBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApUnlikesBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP不喜欢行为表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-01-21
 */
@Service
public class ApUnlikesBehaviorServiceImpl extends ServiceImpl<ApUnlikesBehaviorMapper, ApUnlikesBehavior> implements IApUnlikesBehaviorService {

    @Autowired
    private IApBehaviorEntryService entryService;

    @Override
    public ResponseResult saveUnlikes(UnLikesBehaviorDto dto) {
        // 获取当前登录的用户
        User user = UserThreadLocalUtil.get();
        // 获取行为实体
        ApBehaviorEntry entry = entryService.getEntry(dto.getUserId(), dto.getEquipmentId());
        // 构建不喜欢行为对象
        ApUnlikesBehavior behavior = new ApUnlikesBehavior();
        behavior.setEntryId(entry.getId());
        behavior.setArticleId(dto.getArticleId());
        behavior.setType(dto.getType());
        behavior.setCreatedTime(new Date());
        // 判断是否已经有历史记录
        LambdaQueryWrapper<ApUnlikesBehavior> query = new LambdaQueryWrapper<>();
        query.eq(ApUnlikesBehavior::getArticleId, dto.getArticleId());
        query.eq(ApUnlikesBehavior::getEntryId, entry.getId());
        ApUnlikesBehavior one = this.getOne(query);
        if (one == null) {
            this.save(behavior);
        } else {
            if (!one.getType().equals(dto.getType())) {
                one.setType(dto.getType());
                this.updateById(one);
            }
        }
        return ResponseResult.okResult();
    }


    @Override
    public ResponseResult<ApUnlikesBehavior> getUnlikes(UnLikesBehaviorDto dto) {
        // 根据行为实体id和文章id查询
        LambdaQueryWrapper<ApUnlikesBehavior> query = new LambdaQueryWrapper<>();
        query.eq(ApUnlikesBehavior::getEntryId, dto.getEntryId());
        query.eq(ApUnlikesBehavior::getArticleId, dto.getArticleId());
        ApUnlikesBehavior one = this.getOne(query);
        return ResponseResult.okResult(one);
    }

}
